<template>
  <!-- 数据列表  -->
  <div v-show="!vMode || vMode === 'list'">
    <van-nav-bar title="族人列表" left-text="返回" left-arrow @click-left="goHome" fixed>
      <template #right>
        <van-icon name="ellipsis" size="18" @click="listActShw = true" />
      </template>
    </van-nav-bar>
    <p style="margin-top: 40px"></p>
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" offset="10" @load="onLoad">
      <!--@todo tab 显示用信息-->
      <van-cell v-for="item in vList" :key="item.id" :label="`最近更新： ${item.mtime}, 父: ${item.father}`" icon="user-o"
        is-link @click="viewUser(item)">
        <template #title>
          <span class="custom-title">{{ item.name }}</span>
          <van-tag type="primary" v-if="item.gender === 1">男</van-tag>
          <van-tag type="success" v-if="item.gender === 2">女</van-tag>
        </template>
      </van-cell>
    </van-list>
    <van-action-sheet v-model:show="listActShw" :actions="listActions" cancel-text="取消" close-on-click-action
      @cancel="listActShw = false" @select="lsActSelect" />
    <van-dialog v-model:show="vSearch.show" title="族人搜索" show-cancel-button @confirm="clanSearch">
      <van-cell center title="父子搜索">
        <template #right-icon>
          <van-switch v-model="vSearch.child_mk" size="24" />
        </template>
      </van-cell>
      <van-search v-model="vSearch.value" placeholder="请输入搜索关键词" @keydown="clanSearchKeydown" />
    </van-dialog>
  </div>
  <!-- 数据详情  -->
  <div v-show="vMode === 'view'">
    <van-nav-bar :title="vUser.name" left-text="返回" left-arrow @click-left="vMode = 'list'" />
    <van-cell center title="姓名" :value="vUser.name" />
    <van-cell center title="性别" :value="vUser.gender === 2 ? '女' : '男'" />
    <van-cell center title="生日" v-show="vUser.birthday" :value="vUser.birthday" />
    <van-cell center title="忌日" v-show="vUser.deathday" :value="vUser.deathday" />
    <van-cell title="父亲" :value="vUser.father" :is-link="'' !== vUser.father" v-show="vUser.father"
      @click="viewUser(vUser.fm_id)" />
    <van-cell title="母亲" :value="vUser.mother" :is-link="'' !== vUser.mother" v-show="vUser.mother"
      @click="viewUser(vUser.mm_id)" />
    <van-cell v-show="vUser.children && vUser.children.length > 0" value="子级列表">
      <template #title>
        <van-tag v-for="item in vUser.children" :key="item.id" :type="item.gender === 1 ? 'primary' : 'success'" round
          @click="viewUser(item.id)">{{ item.name }}</van-tag>
      </template>
    </van-cell>
    <van-cell title="简介" :label="vUser.brief" />
    <van-cell title="备注" v-show="vUser.remark" :label="vUser.remark" />
    <van-cell title="编辑时间" :value="vUser.mtime" />
    <van-cell title="编辑者" :value="vUser.cuser" />
    <div style="margin: 16px; text-align: right" v-if="isAdmin">
      <van-button round type="primary" size="small" @click="onEdit">修改</van-button>
      <van-button round type="danger" size="small" @click="onDelete">删除</van-button>
    </div>
  </div>
  <!--  数据编辑 -->
  <div v-show="vMode === 'edit'">
    <van-nav-bar title="编辑" left-text="返回" left-arrow @click-left="vMode = 'list'" />
    <van-form @submit="onSubmit">
      <van-field v-model="vRow.name" name="name" label="姓名" placeholder="姓名"
        :rules="[{ required: true, message: '请填写姓名' }]" clearable />
      <van-field v-model="vRow.gender" name="gender" label="性别">
        <template #input>
          <van-radio-group v-model="vRow.gender" direction="horizontal">
            <van-radio name="1">男</van-radio>
            <van-radio name="2">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-model="vRow.zibei" v-if="vClan.hasRank" name="zibei" label="字辈" clearable readonly>
        <template #button>
          <van-button size="small" type="success" plain round @click="onPopup('zibei')">获取</van-button>
        </template>
      </van-field>
      <van-field clickable name="birthday" v-model="vRow.birthday" label="生日" @click="vSetting._showPicker = true"
        clearable />
      <van-popup v-model:show="vSetting._showPicker" position="bottom">
        <van-date-picker type="date" @confirm="onBirthdayConfirm" @cancel="vSetting._showPicker = false"
          :min-date="vSetting.minDate" :max-date="vSetting.maxDate" />
      </van-popup>
      <van-field v-model="vRow.deathday" name="deathday" label="忌日" placeholder="请填写正确的日期格式" clearable />
      <van-field v-model="vSetting.truth_mk_show" readonly clickable name="truth_mk" label="真实性"
        @click="vSetting._truthMkShwPck = true" />
      <van-popup v-model:show="vSetting._truthMkShwPck" position="bottom">
        <van-picker :columns="vSetting._truthMkOption" @confirm="onTruthMkConfirm"
          @cancel="vSetting._truthMkShwPck = false" />
      </van-popup>
      <van-field v-model="vRow.mother" name="mother" label="母亲" clearable @blur="onPopup('mother', true)">
        <template #button>
          <van-button size="small" type="success" plain round @click="onPopup('mother')">获取</van-button>
        </template>
      </van-field>
      <van-field v-model="vRow.father" name="father" label="父亲" clearable @blur="onPopup('father', true)">
        <template #button>
          <van-button size="small" type="success" plain round @click="onPopup('father')">获取</van-button>
        </template>
      </van-field>
      <!-- 公共 popup -->
      <van-popup v-model:show="vSetting._popup" position="bottom">
        <van-picker :columns="vSetting._popupOption" @confirm="onPopupConfirm" @cancel="vSetting._popup = false" />
      </van-popup>
      <van-field v-model="vRow.brief" name="brief" rows="4" autosize label="简介" type="textarea" placeholder="请输入简介"
        clearable />
      <van-field v-model="vRow.remark" name="remark" rows="2" autosize label="备注" type="textarea" clearable />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import {
  showConfirmDialog,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
} from "vant";
import { Wap } from "../../../common/wap";
import { ref, onMounted } from "vue";
import type { Ref } from "vue";
import { useRoute, useRouter } from "vue-router";

// 路由地址
const route = useRoute();
const router = useRouter();
const params = route.params;

//新增初始化
const addInitRow = {
  id: 0,
  name: "",
  gender: 1,
  rank_id: 0,
  zibei: "",
  birthday: "",
  deathday: "",
  clan_id: params.clan_id,
  remark: "",
  muid: "",
  mtime: "",
  mm_id: 0,
  fm_id: 0,
  mother: "",
  father: "",
  brief: "",
  truth_mk: 0,
  ctime: "",
  del_mk: "",
};
const curYear = new Date().getFullYear() + 20;
// 分页缓存
let cPg = {
  current: 0,
  pageSize: 15,
};

// 数据定义
const vList: Ref<Array<KvObj>> = ref([]);
const loading = ref(false);
const finished = ref(false);
const vUser: Ref<KvObj> = ref({});
const listActShw = ref(false);
const listActions: Ref<Array<KvObj>> = ref([]);
const isAdmin = ref(false);
const vMode = ref("");
const vSearch = ref({
  show: false,
  value: "",
  child_mk: false,
});
const formInit: Ref<KvObj> = ref(addInitRow);
const vRow: Ref<KvObj> = ref(addInitRow);
const _popupOption: Array<KvObj> = [];
const vSetting = ref({
  minDate: new Date(1000, 0, 1),
  maxDate: new Date(curYear, 0, 1),
  _truthMkOption: [
    { text: "可靠", value: 1 },
    { text: "无法考证", value: 0 },
    { text: "虚设", value: -1 },
    { text: "疑似虚设", value: -4 },
  ],
  _popup: false,
  _popupOption,
  _popupCurKey: "",
  _showPicker: false,
  _truthMkShwPck: false,
  truth_mk_show: "无法考证",
});
const vClan: Ref<KvObj> = ref({});

// 方法定义
function goHome() {
  router.push({ path: `/clan/${params.clan_id}` });
}

// 成员加载
function loadMember(postData?: KvObj | null, flushMk?: boolean) {
  if (flushMk) {
    cPg.current = 1;
  }
  postData = postData || {};
  postData.clan_id = params.clan_id;
  postData = Object.assign({}, cPg, postData);
  Wap.post("/square/data/clan/member/view", postData)
    .then((result) => {
      if (result.status === "ok") {
        let data = result.data;
        let list = data.list || [];
        //保留旧的值
        let oData = vList.value || [];
        if (!list || list.length === 0) {
          finished.value = true;
          loading.value = false;
        } else {
          loading.value = false;
          finished.value = false;
        }
        if (!flushMk) {
          list = oData.concat(list);
        }
        vList.value = list;
      } else {
        finished.value = true;
        loading.value = false;
        showFailToast(result.msg);
      }
    })
    .catch((error) => {
      console.log(error);
      finished.value = true;
    });
}

// 数据加载
function onLoad() {
  cPg.current += 1;
  loadMember();
}

//用户查看
function viewUser(info: KvObj) {
  let mId = null;
  //统一查询程序
  if ("object" === typeof info) {
    vMode.value = "view";
    mId = info.id;
  } else if (info) {
    mId = info;
  }
  //获取数据
  Wap.get(`/square/data/clan/member/record?id=${mId}`)
    .then((result) => {
      let uData = result.data || {};
      uData.children = uData.children || [];
      vUser.value = uData;
    })
    .catch((error) => {
      console.log(error);
    });
}


function lsActSelect(item?: KvObj) {
  item = item || {};
  switch (item.key) {
    case "search":
      vSearch.value.show = true;
      break;
    case "add":
      vRow.value = formInit.value;
      vMode.value = "edit";
      break;
  }
}

//族人搜索
function clanSearch() {
  let { value } = vSearch.value;
  cPg.current = 0;
  //@todo `keyword` 支持多字段搜索
  let post = {
    s_keyword: "name|remark|brief",
    s_value: value,
  };
  cPg = Object.assign({}, cPg, post);
  loadMember(post, true);
}

function clanSearchKeydown(e: any) {
  switch (e.which) {
    case 13:
      vSearch.value.show = false;
      clanSearch();
      break;
  }
}

function onSubmit(values: KvObj) {
  let postData = Object.assign({}, vRow.value, values);
  //删除无须无须保存值
  ["ctime", "father", "mother", "mtime", "muid", "zibei"].forEach(
    (filter) => {
      if ("undefined" === typeof postData[filter]) {
        delete postData[filter];
      }
    }
  );
  postData.truth_mk = isNaN(postData.truth_mk) ? 0 : postData.truth_mk;

  let loading = showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    message: "数据提交中",
  });
  Wap.post("/square/data/clan/member/save", postData)
    .then((result) => {
      Wap.resolveResponse(result)
        .then(() => {
          if (!vRow.value.id) {
            vRow.value.name = "";
          }
          showSuccessToast(result.msg);
          loadMember(null, true);
        })
        .catch((msg) => {
          showFailToast(msg);
        });
    })
    .finally(() => {
      loading.close();
    });
}


function onBirthdayConfirm(time: Date) {
  vRow.value.birthday = Wap.dateFormat(time);
  vSetting.value._showPicker = false;
}


function onTruthMkConfirm(item: KvObj) {
  vSetting.value._truthMkShwPck = false;
  vSetting.value.truth_mk_show = item.text;
  vRow.value.truth_mk = item.value;
}

/**
     * 公共的开启 popup 的方法
     * @param {string} key
     * @param {boolean} [require]
     */
function onPopup(key: string, require?: boolean) {
  vSetting.value._popupCurKey = key;
  let clanId = params.clan_id,
    url,
    search;
  switch (key) {
    case "zibei":
      vSetting.value._popupOption = vClan.value.rank_list;
      vSetting.value._popup = true;
      break;
    //设置字辈属性
    case "mother":
      search = vRow.value.mother;
      if (require && !search) {
        return;
      }
      url = `/square/data/clan/member?clan_id=${clanId}&keyword=mother&value=${search}`;
      Wap.get(url).then((result) => {
        let data = result.data || [],
          newData: Array<KvObj> = [];
        data.forEach((mem: KvObj) => {
          newData.push({ text: `${mem.id}-${mem.name}`, value: mem.id });
        });
        vSetting.value._popupOption = newData;
        vSetting.value._popup = true;
      });
      break;
    case "father":
      search = vRow.value.father;
      if (require && !search) {
        return;
      }
      url = `/square/data/clan/member?clan_id=${clanId}&keyword=father&value=${search}`;
      Wap.get(url).then((result) => {
        let data = result.data || [],
          newData: Array<KvObj> = [];
        data.forEach((mem: KvObj) => {
          newData.push({ text: `${mem.id}-${mem.name}`, value: mem.id });
        });
        vSetting.value._popupOption = newData;
        vSetting.value._popup = true;
      });
      break;
  }
}

//确认时处理
function onPopupConfirm(item: KvObj | null) {
  if (!item) {
    vSetting.value._popup = false;
    return;
  }
  let key = vSetting.value._popupCurKey;
  switch (key) {
    case "zibei":
      vRow.value.zibei = item.text;
      vRow.value.rank_id = item.value;
      break;
    case "mother":
      vRow.value.mother = item.text;
      vRow.value.mm_id = item.value;
      break;
    case "father":
      vRow.value.father = item.text;
      vRow.value.fm_id = item.value;
      break;
  }
  vSetting.value._popup = false;
}


function onEdit() {
  vRow.value = vUser.value;
  vMode.value = "edit";
}

function onDelete() {
  showConfirmDialog({
    title: "提示",
    message: "您确定要删除数据吗，删除后不可撤销？",
  }).then(() => {
    // on confirm
    let loading = showLoadingToast({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: "数据提交中",
    });
    Wap.post("/square/data/clan/member/del", {
      id: vUser.value["id"],
    })
      .then((result) => {
        Wap.resolveResponse(result)
          .then(() => {
            loadMember(null, true);
            showSuccessToast(result.msg);
            vMode.value = "list";
          })
          .catch((msg) => {
            showFailToast(msg);
          });
      })
      .finally(() => {
        loading.close();
      });
  });
}


// 事件调用
onMounted(function () {
  //获取字辈等信息
  Wap.get(`/square/data/clan?clan_id=${params.clan_id}`).then((result) => {
    let data = result.data;
    data.hasRank = false;
    if (data.rank_list && data.rank_list.length > 0) {
      data.hasRank = true;
      let newRank: Array<KvObj> = [];
      data.rank_list.forEach((rank: { rank: string; id: number }) => {
        newRank.push({ text: rank.rank, value: rank.id });
      });
      data.rank_list = newRank;
    } else {
      data.rank_list = [];
    }
    vClan.value = data || {};
    let is_admin = data["is_admin"];
    let lstActions: Array<KvObj> = [{ name: "搜索", key: "search" }];
    if (is_admin) {
      lstActions.push({ name: "新增成员", key: "add" });
    }
    isAdmin.value = is_admin;
    listActions.value = lstActions;
  });
});
</script>
